package com.dudo.model;
import java.util.ArrayList;
import java.util.Arrays;

public class SimpleDudoPlayer implements DudoPlayer {
	static final double EPSILON = 1e-9; // floating point error threshold
	int playerNum;
	int[] playerNumDice; 
	int[] roll;
	ArrayList<Claim> claimList = new ArrayList<Claim>();
	ArrayList<Integer> claimPlayerList = new ArrayList<Integer>();
	int[][] allRolls;
	int totalDice;
	int[] diceCount = new int[7];

	@Override
	public void setPlayer(int playerNum) {
		this.playerNum = playerNum;
	}

	@Override
	public void reportPlayerDice(int[] playerNumDice) {
		this.playerNumDice = playerNumDice;
		claimPlayerList.clear();
		claimList.clear();
		totalDice = 0;
		for (int numDice : playerNumDice)
			totalDice += numDice;
	}

	@Override
	public void setRoll(int[] roll) {
		this.roll = roll;
		Arrays.sort(roll);
		for (int rank = 1; rank <= 6; rank++)
			diceCount[rank] = 0;
		for (int rank : roll)
			diceCount[rank]++;
	}

	@Override
	public void reportClaim(int player, Claim claim) {
		claimPlayerList.add(player);
		claimList.add(claim);
	}

	@Override
	public void reportAllRolls(int[][] allRolls) {
		this.allRolls = allRolls;
	}

	@Override
	/* Pick the highest claim having >= 50% chance of success.
	 * If no such claim exists, pick the claim or dudo challenge having the greatest 
	 * chance of success.
	 */
	public Claim getClaim() {
		ArrayList<Claim> claims = Claim.diceClaims.get(totalDice);

		//In the event of no previous claim, start with first valid claim for comparison.
		int lastClaimIndex = 0;
		Claim chosenClaim = claims.get(0);
		double claimProb = Claim.getRollProb(totalDice, chosenClaim, roll);
		if (!claimList.isEmpty()) { // If previous claim exists, start with dudo default.
			Claim lastClaim = claimList.get(claimList.size() - 1);
			lastClaimIndex = claims.indexOf(lastClaim);
			chosenClaim = claims.get(claims.size() - 1); // dudo challenge
			claimProb = 1.0 - Claim.getRollProb(totalDice, lastClaim, roll);
		}
		for (int i = lastClaimIndex + 1; i < claims.size() - 1; i++) {
			double prob = Claim.getRollProb(totalDice, claims.get(i), roll);
			// Find strongest non-dudo claim that meets or exceeds .5 probability
			if (prob >= .5 - EPSILON || (claimProb < .5 + EPSILON && prob > claimProb - EPSILON)) {
				chosenClaim = claims.get(i);
				claimProb = prob;
			}
		}
		GameManager.getObject().receiveClaim(chosenClaim.getNum(), chosenClaim.getRank());
		return chosenClaim;
	}

	@Override
	public String toString() {
		String s="";
		for (int die : roll) {
			s += die + "\t";
		}
		s += "\n";
		return s;
	}
}